import React, { Component } from 'react'
import { TableCustomize, compareNum, openModalMessage, openSuccessModal } from './TableCustomize'
import { Upload, Icon, Modal, Button, Drawer } from 'antd';
import { BasicLayout } from '../../../components/BasicLayout'
import AddForm from './AddForm';
import * as APIService from '../../../axios/api_yq'
import { baseUrl } from '../../../config'
const { confirm } = Modal;
function getBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}
export default class Precision extends Component {
    state = {
        dataSource: [
        ],
        columns: [
            {
                title: '序号',
                dataIndex: 'number',
                width: 50,
                ellipsis: true,
                render: (text, record, index) =>
                    <div>
                        {index + 1}
                    </div>
            },
            {
                title: '类型',
                dataIndex: 'type',
                sorter: (a, b) => compareNum(a.type, b.type),
                width: 80,
                ellipsis: true,
                editable: true,
            },
            {
                title: '测量点',
                dataIndex: 'measuringPoint',
                sorter: (a, b) => compareNum(a.measuringPoint, b.measuringPoint),
                width: 100,
                ellipsis: true,
                editable: true,

            },
            {
                title: '最小标准值',
                dataIndex: 'standardMin',
                sorter: (a, b) => compareNum(a.standardMin, b.standardMin),
                width: 150,
                ellipsis: true,
                editable: true,

            },
            {
                title: '最大标准值',
                dataIndex: 'standardMax',
                sorter: (a, b) => compareNum(a.standardMax, b.standardMax),
                width: 150,
                ellipsis: true,
                editable: true,

            },
            {
                title: '单位',
                dataIndex: 'unit',
                sorter: (a, b) => compareNum(a.unit, b.unit),
                width: 100,
                ellipsis: true,
                editable: true,
            },
            {
                title: '备注',
                dataIndex: 'remark',
                width: 100,
                ellipsis: true,
                editable: true,
            },
            {
                title: '操作',
                dataIndex: 'opts',
                render: (text, record) =>
                    <div>
                        <a onClick={() => this.delete(record)}>{'删除'}</a>
                    </div>
            },
        ],
        fileList: [
            // {
            //     uid: '-1',
            //     name: 'image.png',
            //     status: 'done',
            //     url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
            // },
            // {
            //     uid: '-2',
            //     name: 'image.png',
            //     status: 'done',
            //     url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
            // },
        ],
        loading: true,
        buttonLoading: false
    }
    //初始化加载数据
    fetch = (page = 1, size = 10) => {
        this.setState({
            loading: true,
            paging: {
                pageNum: page, pageSize: size
            }
        })
        let a = { pageNum: page, pageSize: size }
        setTimeout(() => {
            this.search({ ...a })
        }, 300);
    }
    // 挂载完成
    componentDidMount() {
        this.fetch();
    }
    // 查询接口
    search = (paging) => {
        APIService.queryRackPageList(paging).then((item) => {
            if (item.data.code === 200) {
                this.setState({
                    loading: false,
                    dataSource: item.data.data.data
                })
                console.log('这是初始化数据', item);
            } else {
                openModalMessage('error', item.data.msg)
            }
        })
    }
    //新增/编辑接口
    newOrCompile = (value) => {
        APIService.alterRackStandard(value).then((item) => {
            if (item.data.code === 200) {
                openSuccessModal(item.data.msg)
                this.handleCancel1()
                this.fetch()
            } else {
                this.setState({
                    buttonLoading: false
                })
                openModalMessage('error', item.data.msg)
            }
        })
    }
    // 单行删除
    delete = (b) => {
        const then = this
        let id = `idList= ${[b.id]}`
        confirm({
            title: '确认删除当项吗，这将影响其他数据模块?',
            onOk() {
                APIService.deleteRackStandard(id).then((item) => {
                    if (item.data.code === 200) {
                        then.fetch()
                        openSuccessModal('删除成功')
                    } else {
                        openModalMessage('error', item.data.msg)
                    }
                })
            },
            onCancel() {
            },
        })
    }
    // 新增  
    newAdd = () => {
        this.setState({
            drawerVisible: true,
            one: false,
            formData: {}
        })
    }
    // table上直接修改数据
    loadData = (value, dataSource) => {
        console.log('在表格修改数据后保存的数据:', value, dataSource);
        this.newOrCompile(value)
    }
    // 确定新增
    onHandleOk = () => {
        const { formData } = this.state
        this.formDrawer.validateFields((err, value) => {
            if (err) return
            let formData1 = { id: formData.id, ...value }
            this.setState({
                buttonLoading: true
            }, () => {
                this.newOrCompile(formData1)
            })
        })
    }
    // 关闭新增
    handleCancel1 = () => {
        this.formDrawer && this.formDrawer.resetFields();
        this.setState({
            drawerVisible: false,
            one: false,
            formData: {},
            buttonLoading: false
        })
    }

    // 上传图片
    // 关闭
    handleCancel = () => this.setState({ previewVisible: false });

    // 点击小眼睛时触发
    handlePreview = async file => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }
        this.setState({
            previewImage: file.url || file.preview,
            previewVisible: true,
        });
    };
    // 获取到上传的图片信息
    handleChange = ({ file, fileList, event }) => {
        const { status, response } = file
        this.setState({ fileList })
        console.log('status', status);
        if (status === 'done') {
            console.log('response', response);
            if (response.code === 200) {
                console.log(1);
            }

        }
    };
    // 点击删除按钮时
    handleRemove = (file) => {
        console.log(file);
        confirm({
            title: '确定要删除吗?',
            // content: 'Some descriptions',
            onOk() {
                console.log('OK');
            },
            onCancel() {
                console.log('Cancel');
            },
        });
        // let uriProp = "?id=" + file.id;
        // let uri = APIService.xxx + uriProp;

        // if (this.props.page === "xxx") {
        //     uri = APIService.xxx + uriProp;
        // }

        // let options = {};

        // return fetch(uri, options)
        //     .then((response) => {
        //         message.success(`${file.name} 删除成功`);
        //     }).catch((err) => {
        //         console.log(err);
        //     });
    };
    // table数据发生改变时
    handleTableChange = (pagination, filters, sorter) => {
        console.log('table数据发生改变时', pagination, filters, sorter);
    }

    render() {
        const { buttonLoading, columns, dataSource, loading, previewVisible, previewImage, fileList, formData, drawerVisible, one } = this.state
        const uploadButton = (
            <div>
                <Icon type="plus" />
                <div className="ant-upload-text">上传图片</div>
            </div>
        );
        const proprs = {
            name: 'file',
            action: `${baseUrl}/lw-mes-file/file/uploadFile`,
            // 上传格式
            listType: "picture-card",
            headers: {
                userId: localStorage.getItem('userId'),
                Token: localStorage.getItem('token'),
            },
            // 已经上传的展示
            fileList: fileList,
            // 点击小眼睛回调            onPreview: this.handlePreview,

            onChange: this.handleChange,
            // 按住ctrl多选上传
            // multiple: true,
            // 点击删除按钮时
            onRemove: this.handleRemove,

        }
        return (
            <div>
                <BasicLayout name='测量点'>
                    <TableCustomize onChange={this.handleTableChange} columns={columns} dataSource={dataSource} rowKey={(record) => record.id} loading={loading} allowDrafting={true} allowEditable={this.loadData} pagination={false}></TableCustomize>
                    <Button type="dashed" onClick={this.newAdd.bind(this)} style={{ width: '100%', marginTop: '10px' }}>
                        <Icon type="plus" />新增
                    </Button>
                </BasicLayout>
                <BasicLayout name='图片'>
                    <div className="clearfix">
                        <Upload
                            {...proprs}
                        // 还没对接好！
                        >
                            {uploadButton}
                        </Upload>                                    {/* 点击遮罩层等关闭  */}
                        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                            <img alt="example" style={{ width: '100%' }} src={previewImage} />
                        </Modal>
                    </div>
                </BasicLayout>
                <Drawer width={500} visible={drawerVisible} title={'新增'} onClose={this.handleCancel1} destroyOnClose>
                    <AddForm
                        formData={formData}
                        onOk={this.onHandleOk}
                        ref={node => (this.formDrawer = node)}
                        onClose={this.handleCancel1}
                        one={one}
                    />
                    <div
                        style={{
                            position: 'absolute',
                            right: 0,
                            bottom: 0,
                            width: '100%',
                            borderTop: '1px solid #e9e9e9',
                            padding: '10px 16px',
                            background: '#fff',
                            textAlign: 'right',
                        }}
                    >
                        <Button onClick={this.handleCancel} style={{ marginRight: 10 }}>{'取消'}</Button>
                        <Button type="primary" onClick={this.onHandleOk} loading={buttonLoading}>
                            {'确认'}
                        </Button>
                    </div>
                </Drawer>
            </div>
        )
    }
}
